package org.example.com.service.impl;

import org.example.com.mapper.*;
import org.example.com.pojo.*;
import org.example.com.pojo.vo.PostCommentVO;
import org.example.com.pojo.vo.PostImageVO;
import org.example.com.pojo.vo.PostTopicVO;
import org.example.com.pojo.vo.PostVO;
import org.example.com.service.PostService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 帖子Service实现类
 */
@Service
public class PostServiceImpl implements PostService {
    
    @Autowired
    private PostMapper postMapper;
    
    @Autowired
    private PostImageMapper postImageMapper;
    
    @Autowired
    private PostTopicMapper postTopicMapper;
    
    @Autowired
    private PostLikeMapper postLikeMapper;
    
    @Autowired
    private PostCommentMapper postCommentMapper;
    
    @Override
    @Transactional
    public Post createPost(Post post, List<String> images, List<String> topics) {
        // 设置默认值
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setShareCount(0);
        post.setStatus("active");
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());
        
        // 插入帖子
        postMapper.insert(post);
        
        // 插入图片
        if (images != null && !images.isEmpty()) {
            List<PostImage> postImages = new ArrayList<>();
            for (int i = 0; i < images.size(); i++) {
                PostImage postImage = new PostImage();
                postImage.setPostId(post.getId());
                postImage.setImageUrl(images.get(i));
                postImage.setImageOrder(i + 1);
                postImage.setCreatedAt(LocalDateTime.now());
                postImages.add(postImage);
            }
            postImageMapper.insertBatch(postImages);
        }
        
        // 插入话题标签
        if (topics != null && !topics.isEmpty()) {
            List<PostTopic> postTopics = new ArrayList<>();
            for (String topicName : topics) {
                PostTopic postTopic = new PostTopic();
                postTopic.setPostId(post.getId());
                postTopic.setTopicName(topicName);
                postTopic.setCreatedAt(LocalDateTime.now());
                postTopics.add(postTopic);
            }
            postTopicMapper.insertBatch(postTopics);
        }
        
        return post;
    }
    
    @Override
    public List<PostVO> getPosts(Integer page, Integer limit, Integer currentUserId) {
        int offset = (page - 1) * limit;
        List<PostVO> posts = postMapper.selectPage(offset, limit, currentUserId);
        
        // 填充关联数据
        for (PostVO post : posts) {
            fillPostDetails(post);
        }
        
        return posts;
    }
    
    @Override
    public List<PostVO> getPostsByUserId(Integer userId, Integer page, Integer limit, Integer currentUserId) {
        int offset = (page - 1) * limit;
        List<PostVO> posts = postMapper.selectByUserId(userId, offset, limit);
        
        // 填充关联数据
        for (PostVO post : posts) {
            fillPostDetails(post);
        }
        
        return posts;
    }
    
    @Override
    public PostVO getPostById(Integer id, Integer currentUserId) {
        Post post = postMapper.selectById(id);
        if (post == null) {
            return null;
        }
        
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        
        // 填充关联数据
        fillPostDetails(postVO);
        
        return postVO;
    }
    
    @Override
    @Transactional
    public boolean updatePost(Post post, List<String> images, List<String> topics) {
        // 更新帖子基本信息
        post.setUpdatedAt(LocalDateTime.now());
        int result = postMapper.update(post);
        
        if (result > 0) {
            // 删除原有图片和话题标签
            postImageMapper.deleteByPostId(post.getId());
            postTopicMapper.deleteByPostId(post.getId());
            
            // 插入新图片
            if (images != null && !images.isEmpty()) {
                List<PostImage> postImages = new ArrayList<>();
                for (int i = 0; i < images.size(); i++) {
                    PostImage postImage = new PostImage();
                    postImage.setPostId(post.getId());
                    postImage.setImageUrl(images.get(i));
                    postImage.setImageOrder(i + 1);
                    postImage.setCreatedAt(LocalDateTime.now());
                    postImages.add(postImage);
                }
                postImageMapper.insertBatch(postImages);
            }
            
            // 插入新话题标签
            if (topics != null && !topics.isEmpty()) {
                List<PostTopic> postTopics = new ArrayList<>();
                for (String topicName : topics) {
                    PostTopic postTopic = new PostTopic();
                    postTopic.setPostId(post.getId());
                    postTopic.setTopicName(topicName);
                    postTopic.setCreatedAt(LocalDateTime.now());
                    postTopics.add(postTopic);
                }
                postTopicMapper.insertBatch(postTopics);
            }
            
            return true;
        }
        
        return false;
    }
    
    @Override
    public boolean deletePost(Integer id) {
        return postMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional
    public boolean likePost(Integer postId, Integer userId) {
        // 检查是否已点赞
        PostLike existingLike = postLikeMapper.selectByPostIdAndUserId(postId, userId);
        if (existingLike != null) {
            return false; // 已经点赞过了
        }
        
        // 添加点赞记录
        PostLike postLike = new PostLike();
        postLike.setPostId(postId);
        postLike.setUserId(userId);
        postLike.setCreatedAt(LocalDateTime.now());
        
        int result = postLikeMapper.insert(postLike);
        if (result > 0) {
            // 增加点赞数
            postMapper.incrementLikeCount(postId);
            return true;
        }
        
        return false;
    }
    
    @Override
    @Transactional
    public boolean unlikePost(Integer postId, Integer userId) {
        // 删除点赞记录
        int result = postLikeMapper.delete(postId, userId);
        if (result > 0) {
            // 减少点赞数
            postMapper.decrementLikeCount(postId);
            return true;
        }
        
        return false;
    }
    
    @Override
    public boolean sharePost(Integer postId) {
        return postMapper.incrementShareCount(postId) > 0;
    }
    
    /**
     * 填充帖子详情数据
     */
    private void fillPostDetails(PostVO post) {
        // 填充图片
        List<PostImage> images = postImageMapper.selectByPostId(post.getId());
        List<PostImageVO> imageVOs = new ArrayList<>();
        for (PostImage image : images) {
            PostImageVO imageVO = new PostImageVO();
            BeanUtils.copyProperties(image, imageVO);
            imageVOs.add(imageVO);
        }
        post.setImages(imageVOs);
        
        // 填充话题标签
        List<PostTopic> topics = postTopicMapper.selectByPostId(post.getId());
        List<PostTopicVO> topicVOs = new ArrayList<>();
        for (PostTopic topic : topics) {
            PostTopicVO topicVO = new PostTopicVO();
            BeanUtils.copyProperties(topic, topicVO);
            topicVOs.add(topicVO);
        }
        post.setTopics(topicVOs);
        
        // 填充评论（只显示前几条）
        List<PostCommentVO> comments = postCommentMapper.selectByPostId(post.getId(), 0, 5);
        post.setComments(comments);
    }
}
